// app.js
const token = wx.getStorageSync("cookie");
import PubSub from './utils/pubsub';
App({
  onShow() {
    // 得到聊天列表
    this.getChatList();
    
    this.userLogin();
    // 登录
    // this.socket();
  },

  userLogin() {
    const cookie = wx.getStorageSync("cookie");
    const that  = this;
    if (cookie) {
      wx.request({
        url: "http://gzhu.vaiwan.com/ct",
        method: "POST",
        data: {
          access_token: cookie,
        },
        header: {
          "Content-type": "application/x-www-form-urlencoded",
        },
        success: (result) => {
          
          console.log("检测是否登录token是否过期", result.data.data);
          // 如果token为空，表示登录状态过期了
          if (result.data.data.access_token === null) {
            wx.removeStorageSync("cookie");
            wx.setStorageSync("isLogin", false);
          }else{
            // 有效登录就发起websocket连接
            that.socket();
          }
        },
        fail: (err) => {
          console.log("失败", err);
        },
      });
    }
  },

  // socket
  // 私聊
  async socket() {
    // console.log(token);
    const that = this;

    this.globalData.sockTask = await wx.connectSocket({
      url: "ws://gzhu.netty.vaiwan.com/ws",
    });

    // readyState === 1 连接成功
    console.log('连接状态：',this.globalData.sockTask);

    this.globalData.sockTask.onOpen(() => {
      console.log("连接成功");

      that.globalData.sockTask.send({
        data: JSON.stringify({
          data: "你好",
          access_token: token,
          type: 1,
        }),
        success(res) {
          console.log("发送数据", res);
        },
        fail(err) {
          console.log("发送数据事变", err);
        },
      });

      // 接收消息
      that.globalData.sockTask.onMessage((res) => {
        const result = JSON.parse(res.data);
        console.log("发布者：", result);

        // 发布方
        PubSub.publish('dialog',result);
      });

    });

    // 当连接是不正常关闭，则调用这个函数
    this.globalData.sockTask.onClose(err=>{
      console.log(err.code);
      if(err.code!==1000){
        that.socket();
      }
    })

  },

  // 得到聊天列表
  getChatList(){
    const that = this;
    wx.request({
      url: `http://gzhu.vaiwan.com/chat?access_token=${token}`,
      method: 'GET',
      success: (res) => {
        console.log('聊天列表',res.data);
        const result = res.data;
        if(result.code!==200){
          return;
        }
        that.globalData.chatList=res.data.data
      },
    });
  },

  globalData: {
    OPENID: "",
    sockTask:null,
    // 聊天列表
    chatList:[],
    edit_goodsid:-1
  },
});
